package com.salim.leetcode.$35;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SearchInsertPosition {
    public int searchInsert(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            if (nums[mid] == target) {
                return mid;
            }
            if (nums[mid] > target) {
                if(mid-1<0){
                    return 0;
                }
                if(nums[mid-1]<target){
                    return mid;
                }else{
                    right = mid - 1;
                }
            } else {
                if(mid+1>=nums.length){
                    return mid+1;
                }
                if(nums[mid+1]>target){
                    return mid + 1;
                }else{
                    left = mid + 1;
                }
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        SearchInsertPosition s = new SearchInsertPosition();
        log.info("SearchInsertPosition输出结果1：{}", s.searchInsert(new int[]{1,3,5,6}, 5));
        log.info("SearchInsertPosition输出结果2：{}", s.searchInsert(new int[]{1,3,5,6}, 2));
        log.info("SearchInsertPosition输出结果3：{}", s.searchInsert(new int[]{1,3,5,6}, 7));
        log.info("SearchInsertPosition输出结果4：{}", s.searchInsert(new int[]{1,3,5,6}, 0));
    }
}
